<template>
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
    <!-- prop用来和rules 中的名称队形 用来验证的 -->
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.goodsName" />
      </el-form-item>
      <el-form-item label="商品图片" prop="name">
        <el-upload
    class="avatar-uploader"
    action="http://localhost:23892/api/Upload/UploadFile"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img  v-if="ruleForm.goodsImg" :src="ruleForm.goodsImg" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon" >
      <Plus />
    </el-icon> 
  </el-upload>
      </el-form-item>
      <el-form-item label="商品价格" prop="name">
        <el-input v-model="ruleForm.goodsPrice" />
      </el-form-item>
      <el-form-item label="商品库存" prop="name">
        <el-input-number v-model="ruleForm.goodsInventory" :min="1" :max="50"/>
      </el-form-item>
      <el-form-item label="商品说明" prop="name">
        <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
      />
      <Editor
        style="height: 300px; overflow-y: hidden;"
        v-model="ruleForm.goodsInfo"
        :defaultConfig="editorConfig"
        @onCreated="handleCreated"
      />
    </div>
      </el-form-item>
      <el-form-item label="商品状态" prop="name">
        <el-radio-group v-model="ruleForm.goodsStatus">
           <el-radio :value="true">上架</el-radio>
           <el-radio :value="false">下架</el-radio>
         </el-radio-group>
      </el-form-item>

        <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加商品
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
  import axios from 'axios';
  // import type{AxiosStatic} from 'axios'
  import { ElMessage } from 'element-plus'
  // const axios =inject('axios') as AxiosStatic
  import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
  import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, shallowRef, onMounted } from 'vue'
//@ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...',maxLength:1000 }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor:any) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

  const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response) => {
  if(response.isSuc)
  {
    ruleForm.goodsImg = "http://localhost:23892/"+response.data
  }
  else
  {
    ElMessage.error(response.msg);
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile.type);
  if (rawFile.type !== 'image/jpeg'&&rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be jpg/png format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

  //后端api需要什么参数就定义什么参数
  interface RuleForm {
    goodsName: string,
  goodsImg: string,
  goodsPrice: number,
  goodsInventory: number,
  goodsInfo: string,
  goodsStatus: boolean,
  }
  
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  //定义表单的变量，在这里给ruleForm赋初始值
  const ruleForm = reactive<RuleForm>({
    goodsName: "",
  goodsImg: "",
  goodsPrice: 0,
  goodsInventory: 0,
  goodsInfo: "",
  goodsStatus: true,
  })
  
  //定义表单验证规则
  const rules = reactive<FormRules<RuleForm>>({ })

  //提交表单
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        axios.post('/api/Goods/GoodsAdd',ruleForm)
        .then(res=>{
          if(res.data.isSuc)
          {
            ElMessage.success(res.data.msg);
          }
          else
          {
            ElMessage.error(res.data.msg);
          }
        })

      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
//重置表单
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
 
  </script>
  

  
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>